﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;

using System.IO;
using System.IO.Ports;
using MySql.Data.MySqlClient;
using System.Runtime.CompilerServices;


namespace WebServiceApp
{
    /// <summary>
    /// Summary description for smss_web_service_app
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class smss_web_service_app : System.Web.Services.WebService
    {

        private static string connectionString = " server=localhost; User Id= root; Password= 1234; Persist Security Info= True; database= smss_new ";
        private static MySqlConnection connection = new MySqlConnection(connectionString);


        #region Private Variables
        SerialPort port = new SerialPort();
        clsSMS objclsSMS = new clsSMS();
        ShortMessageCollection objShortMessageCollection = new ShortMessageCollection();
        LeaveApp objClzLeave = new LeaveApp();
        #endregion


        //open connection to database
        [WebMethod]
        public bool OpenConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0: break;

                    case 1045: break;
                }
                return false;
            }
        }

        //Close connection
        [WebMethod]
        public bool CloseConnection()
        {
            try
            {
                connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                return false;
            }
        }


        //not return any data
        [WebMethod]
        public void Modify(String query)
        {
            this.CloseConnection();
            OpenConnection();
            MySqlCommand cmd = new MySqlCommand(query, connection);

            cmd.ExecuteNonQuery();
            CloseConnection();
        }


        //return data
        [WebMethod]
        public DataTable Search(String query)
        {
            DataTable dt = new DataTable("SMSS");

            dt.Columns.Add("testColumn");
            DataRow testRow = dt.NewRow();
            testRow["testColumn"] = "test";
            dt.Rows.Add(testRow);

            try
            {
                this.CloseConnection();
                OpenConnection();

                MySqlCommand cmd = new MySqlCommand(query, connection);

                using (MySqlDataAdapter a = new MySqlDataAdapter(cmd))
                {
                    dt = new DataTable("TB_SMSS");
                    a.Fill(dt);
                }
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                connection.Dispose();
            }

            CloseConnection();
            return dt;
        }

        // insert image file to db
        [WebMethod]
        public void insertImage(String query, byte[] imageByteArray)
        {
            this.CloseConnection();
            OpenConnection();

            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = connection;
            cmd.CommandText = query;


            cmd.Parameters.Add("@image", MySqlDbType.LongBlob);
            cmd.Parameters["@image"].Value = imageByteArray;

            cmd.ExecuteNonQuery();

            CloseConnection();

        } 


        // get serial port name
        [WebMethod]
        private string getSerialPortName()
        {
            string portName;
            DataTable portData;

            try
            {
                portData = Search("select port_name from configurations");
                portName = portData.Rows[0][0].ToString();
            }
            catch(Exception ex)
            {
                throw ex;
            }
            return portName;
        }

        // Initialize the port for sms service
        [WebMethod]
        private string initializePort()
        {
            try
            {
                //Set Port Name
                String portName = getSerialPortName();
                Int32 boundRate = 115200;
                Int32 dataBitRate = 8;
                Int32 readTimeOut = 30000000;
                Int32 writeTimeOut = 30000000;

                //Open communication port 
                this.port = objclsSMS.OpenPort(portName, boundRate, dataBitRate, readTimeOut, writeTimeOut);

                if (this.port == null)
                {
                    return ("Invalid port settings");
                }
                else
                {
                    return ("Valid port settings");
                }
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }

        }


        // read sms for leave application form
        [WebMethod]
        public string ReadSMS_forLeave()
        {
            string message="";
            message = initializePort();

            try
            {
                //count SMS 
                int uCountSMS = objclsSMS.CountSMSmessages(this.port);
                if (uCountSMS > 0)
                {
                    string strCommand = "AT+CMGL=\"ALL\"";

                    // If SMS exist then read SMS
                    #region Read SMS
                    //.............................................. Read all SMS ....................................................
                    objShortMessageCollection = objclsSMS.ReadSMS(this.port, strCommand);
                    foreach (ShortMessage msg in objShortMessageCollection)
                    {
                        if (msg.Status != "read")
                        {
                            SendSMS(objClzLeave.leaveStart(msg.Sender, msg.Message, this.port), msg.Sender);
                        }
                    }
                    #endregion
                }
                else
                {
                    message = "There is no message in SIM";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return message;
        }


        // read sms for substitute teacher allocation
        [WebMethod]
        public string ReadSMS_forSubsTeacher()
        {
            string message = "";
            message = initializePort();

            try
            {
                //count SMS 
                int uCountSMS = objclsSMS.CountSMSmessages(this.port);
                if (uCountSMS > 0)
                {
                    string strCommand = "AT+CMGL=\"ALL\"";

                    // If SMS exist then read SMS
                    #region Read SMS
                    //.............................................. Read all SMS ....................................................
                    objShortMessageCollection = objclsSMS.ReadSMS(this.port, strCommand);
                    foreach (ShortMessage msg in objShortMessageCollection)
                    {
                            message = msg.Message + msg.Sender.ToString();
                    }
                    #endregion
                }
                else
                {
                    message = "There is no message in SIM";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return message;
        }


        // send sms
        [WebMethod]
        public string SendSMS(string msg, string receiver)
        {
            string message="";
            message = initializePort();

            try
            {
                if (objclsSMS.sendMsg(this.port, receiver, msg))
                {
                    message = "Message has sent successfully";
                }
                else
                {
                    message = "Failed to send message";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return message;
        }
        

    }
}
